package Servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(urlPatterns="/admin/login",initParams={
		@WebInitParam(name ="loginName",value="admin"),
	    @WebInitParam(name = "loginPwd", value = "1234")
})
public class LoginServlet extends HttpServlet {
    
	private String saveName;
	private String savePwd;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		req.getRequestDispatcher("/WEB-INF/pages/admin/index.jsp").forward(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String loginName = req.getParameter("loginName");
		String loginPwd = req.getParameter("loginPwd");
		String code = req.getParameter("code");
	    if(code == null)
	    {
	    	code = "";
	    }
		HttpSession session = req.getSession();
		Object obj = session.getAttribute("code");
		if(obj == null || "".equals(obj))
		{
		   //out.println("验证码生成错误");
			   String msg = "验证码生成错误!";
		       resp.sendRedirect("./login?msg="+msg);
		}
		else
		{
			String num = obj.toString().toLowerCase();
			if(num.equals(code.toLowerCase()))
			{	
				if(saveName != null && saveName.equals(loginName)&&savePwd != null && savePwd.equals(loginPwd))
			         //if(loginName != null && !"".equals(loginName))

		         {
		        	     session.setAttribute("user", loginName);
			        	 resp.sendRedirect("./main");
		   	        //out.println(loginName+"，欢迎登陆");
		   	        
		         }
			   else
			      {
				     // out.println("用户名或密码错误");
				     String msg = "用户名或密码错误!";
		        	 resp.sendRedirect("./login?msg="+msg);
			      }
			}
			else
			{
				
				String msg = "验证码输入错误";
			    resp.sendRedirect("./login?msg="+msg);
			}
		}
		
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		saveName = config.getInitParameter("loginName");
		savePwd = config.getInitParameter("loginPwd");
	}

}
